package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishDto;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 菜品管理
 */
@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private DishService dishService;
    @Autowired
    private CategoryService categoryService;

    @Autowired
    private DishFlavorService dishFlavorService;

    /**
     * 新增菜品
     *
     * @param dishDto
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto) {
        log.info(dishDto.toString());
        dishService.saveWithFlavor(dishDto);
        //清理某个分类下面的菜品缓存数据
        String key = "Category_" + dishDto.getCategoryId() + "_status_1";
        redisTemplate.delete(key);
        return R.success("新增菜品成功");
    }

    /**
     * 菜品信息分页查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
        //构造分页构造器对象
        Page<Dish> pageInfo = new Page<>(page, pageSize);
        Page<DishDto> dishDtoPage = new Page<>();
        //条件构造器
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        //添加过滤条件
        queryWrapper.like(name != null, Dish::getName, name);
        //添加排序条件
        queryWrapper.orderByDesc(Dish::getUpdateTime);
        //执行分页查询
        dishService.page(pageInfo, queryWrapper);
        //对象拷贝
        BeanUtils.copyProperties(pageInfo, dishDtoPage, "records");
        List<Dish> records = pageInfo.getRecords();
        List<DishDto> list = records.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);
            Long categoryId = item.getCategoryId();//分类id
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);
            if (category != null) {
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            return dishDto;
        }).collect(Collectors.toList());
        dishDtoPage.setRecords(list);
        return R.success(dishDtoPage);
    }

    @GetMapping("/{id}")
    public R<DishDto> get(@PathVariable String id) {
        DishDto dishdto = dishService.getwithflavor(id);
        return R.success(dishdto);
    }

    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto) {
        dishService.updatedish(dishDto);
        return R.success("修改成功");
    }

    @PostMapping("/status/1")
    public R<String> updateDish(@RequestParam List<Long> ids) {
        System.out.println(ids);
        dishService.updatestatus(ids);
        return R.success("操作成功");
    }

    @PostMapping("/status/0")
    public R<String> updateDish2(@RequestParam List<Long> ids) {
        System.out.println(ids);
        dishService.updatestatus2(ids);
        return R.success("操作成功");
    }

    @DeleteMapping
    private R<String> delectbyid(@RequestParam List<Long> ids) {
        dishService.delectbyids(ids);
        return R.success("删除成功");
    }

    @GetMapping("/list")
    public R<List<DishDto>> get(Long categoryId, String status) {
        //先从缓存中去查询
        String want = "Category_" + categoryId + "_status_" + status;
        List<DishDto> wantList = (List<DishDto>) redisTemplate.opsForValue().get(want);
        //查到了直接返回
        if (wantList != null) {
            return R.success(wantList);
        }
        //在缓存中没有查到，再去MYSQL去查
        //根据分类id查询菜品
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Dish::getCategoryId, categoryId);
        lqw.eq(status != null, Dish::getStatus, status);
        List<Dish> list = dishService.list(lqw);
        List<DishDto> list2 = list.stream().map(new Function<Dish, DishDto>() {
            @Override
            public DishDto apply(Dish dish) {
                DishDto dishDto = new DishDto();
                BeanUtils.copyProperties(dish, dishDto);
                LambdaQueryWrapper<DishFlavor> lqw2 = new LambdaQueryWrapper<>();
                lqw2.eq(DishFlavor::getDishId, dish.getId());
                List<DishFlavor> DishFlavors = dishFlavorService.list(lqw2);
                dishDto.setFlavors(DishFlavors);
                return dishDto;
            }
        }).collect(Collectors.toList());
        //将查好的数据放入缓存中
        redisTemplate.opsForValue().set(want, list2, 60, TimeUnit.MINUTES);
        return R.success(list2);
    }

}    